<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发起方名称" prop="receiverCompanyName" label-width="90px">
        <el-input
          v-model="queryParams.receiverCompanyName"
          placeholder="请输入发起方名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开票状态" prop="status">
        <el-select v-model="queryParams.status">
          <el-option :value="0" label="待开票"></el-option>
          <el-option :value="1" label="待验收"></el-option>
          <el-option :value="2" label="完成"></el-option>
          <el-option :value="3" label="驳回"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开票类型" prop="invoiceType">
        <el-select v-model="queryParams.invoiceType">
          <el-option :value="2" label="普票"></el-option>
          <el-option :value="1" label="专票"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发票类目" prop="invoiceCatagory">
        <el-input
          v-model="queryParams.invoiceCatagory"
          placeholder="请输入发票类目"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['invoice:invoice:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table ref="table" v-loading="loading" :data="payslipList" @select="handleSelectionChange"@select-all="handleSelectionAllChange">
      <el-table-column label="发起方名称" align="center" prop="receiverCompanyName" min-width="180"/>
      <el-table-column label="税额" align="center" prop="taxAmount" show-overflow-tooltip min-width="120"/>
      <el-table-column label="不含税金额" align="center" prop="taskAmount" show-overflow-tooltip min-width="120"/>
      <el-table-column label="补扣额" align="center" prop="deductionAmount" show-overflow-tooltip min-width="120"/>
      <el-table-column label="价税合计" align="center" prop="invoiceAmount" show-overflow-tooltip min-width="120"/>
      <el-table-column label="开票类型" align="center" prop="isInvoicing" width="100">
        <template slot-scope="{ row }">
          <el-tag style="cursor: pointer" v-if="row.invoiceType === 1">专票</el-tag>
          <el-tag style="cursor: pointer" type="warning" v-else-if="row.invoiceType === 2">普票</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开票类目" align="center" prop="invoiceCatagory" min-width="180"/>
      <el-table-column label="发票文件" align="center" prop="invoiceFile" width="100">
        <template slot-scope="{ row }">
          <el-link :href="baseUrl+row.invoiceFile" v-if="row.invoiceFile" :underline="false" target="_blank">
            <el-button type="text" size="mini">查看发票</el-button>
          </el-link>
        </template>
      </el-table-column>

      <el-table-column label="开票状态" align="center" prop="isInvoicing" width="100">
        <template slot-scope="{ row }">
          <el-tag style="cursor: pointer" type="warning" v-if="row.status === 0">待开票</el-tag>
          <el-tag style="cursor: pointer" type="success" v-else-if="row.status === 1">待验收</el-tag>
          <el-tag style="cursor: pointer" v-else-if="row.status === 2">完成</el-tag>
          <el-popover
            placement="bottom"
            title=""
            width="200"
            trigger="click"
            :content="row.reason">
            <el-tag slot="reference" v-if="row.status === 3" style="cursor: pointer" type="danger">驳回</el-tag>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="申请时间" align="center" prop="createTime" width="180"></el-table-column>
      <el-table-column label="开票时间" align="center" prop="invoiceTime" width="180" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status !== 2 "
            @click="handleInvoice(scope.row)"
          >开票</el-button>

          <el-button
            size="mini"
            type="text"
            @click="handleDetail(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-drawer :wrapperClosable="false" :close-on-press-escape="false" destroy-on-close title="开票" :visible.sync="detailOpen" size="70%" append-to-body>
      <el-descriptions title="" border>

        <el-descriptions-item label="发起方" >{{ form.receiverCompanyName }}</el-descriptions-item>
        <el-descriptions-item label="纳税识别号" >{{ form.receiverCreditCode }}</el-descriptions-item>
        <el-descriptions-item label="开票类目">
          <span v-if="organizationType === 1">
              信息技术服务*信息技术服务费
          </span>
          <span v-else-if="organizationType === 2">
            现代服务*推广服务费
          </span>
          <span v-else-if="organizationType === 3">
            {{ form.invoiceCatagory }}
          </span>

        <el-descriptions-item label="不含税金额/元">{{ formattedTotal(form.taxAmount) }}</el-descriptions-item>
        <el-descriptions-item label="价税合计/元">{{ formattedTotal(form.taskAmount) }}</el-descriptions-item>
        <el-descriptions-item label="企业名称">{{ formattedTotal(form.invoiceAmount) }}</el-descriptions-item>

        </el-descriptions-item>
        <el-descriptions-item label="发票">
          <el-link :href="baseUrl+form.invoiceFile" v-if="form.invoiceFile" :underline="false" target="_blank">
            <el-button type="text" size="mini">查看发票</el-button>
          </el-link>
        </el-descriptions-item>

      </el-descriptions>

      <el-table v-loading="loading" :data="invoiceTaskList">
        <el-table-column label="任务名称" align="center" prop="task.taskName" min-width="180"/>
        <el-table-column label="打款金额" v-if="organizationType === 4" align="center" prop="payslip.successAmount">
          <template slot-scope="{ row }">
            <span v-if="row.payslip">
              {{row.payslip.successAmount +row.payslip.successMerchantAmount}}
            </span>
            <span v-else>{{row.invoice.invoiceAmount}}</span>
          </template>
        </el-table-column>
        <el-table-column label="发票类型" align="center" prop="invoice.invoiceType" width="120">
          <template slot-scope="{ row }">
            {{row.invoice.invoiceType===1?'专票':row.invoice.invoiceType===2?'普票':''}}
          </template>
        </el-table-column>
        <el-table-column label="发票类目" align="center" prop="invoice.invoiceCatagory" min-width="180"/>
        <el-table-column label="发票文件" align="center" prop="invoice.invoiceFile" min-width="120">
          <template slot-scope="{ row }">
            <el-link :href="baseUrl+row.invoice.invoiceFile" v-if="row.invoice.invoiceFile" :underline="false" target="_blank">
              <el-button type="text" size="mini">查看发票</el-button>
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="开票时间" align="center" prop="invoice.invoiceTime" width="180" />
      </el-table>
      <pagination
        v-show="invoiceTaskTotal>0"
        :total="invoiceTaskTotal"
        :page.sync="invoiceTaskQuery.pageNum"
        :limit.sync="invoiceTaskQuery.pageSize"
        @pagination="handleDetail"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">取 消</el-button>
      </div>
    </el-drawer>>


    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="开票" :visible.sync="invoiceOpen" width="500px" append-to-body>
      <el-form ref="settlementForm" v-loading="invoiceLoading" :model="form" label-width="100px">
        <el-form-item label="税额/元">
          {{ formattedTotal(form.taxAmount) }}
        </el-form-item>
        <el-form-item label="不含税金额/元">
          {{ formattedTotal(form.taskAmount) }}
        </el-form-item>
        <el-form-item label="价税合计/元">
          {{ formattedTotal(form.invoiceAmount) }}
        </el-form-item>
        <el-form-item label="发起方名称">
          {{ form.receiverCompanyName }}
        </el-form-item>
        <el-form-item label="开票类目">
          {{ form.invoiceCatagory }}
        </el-form-item>
        <el-form-item label="发票" prop="invoiceFile">
          <FileUpload :file-type='["pdf","zip","png", "jpg", "jpeg"]' v-model="form.invoiceFile" :limit="1"
          ></FileUpload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="invoiceLoading" type="primary" @click="subInvoice">立即提交</el-button>
        <el-button :loading="invoiceLoading" @click="invoiceOpen = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import store from '@/store'
import 'splitpanes/dist/splitpanes.css'
import { listTask } from '@/api/system/task'
import { Pane, Splitpanes } from 'splitpanes'
import { listInvoiceTask } from '@/api/invoice/invoiceTask'
import { listCooperativeTax } from '@/api/tax/cooperativeTax'
// import PayslipDetail from '@/views/ecs/payslip/modules/detail.vue'
import { listInvoice, submitPayslipInvoice } from '@/api/invoice/invoice'

export default {
  name: 'pendingInvoicing',
  components: {  Splitpanes, Pane },
  data() {
    return {
      total: 0,
      loading: false,
      detailOpen: false,
      showSearch: true,
      tslLoading: false,
      invoiceOpen: false,
      taskLoading: false,
      invoiceLoading: false,
      tslOptions: [],
      taskOptions: [],
      selectedRowKeys: [],
      merchantLoading: false,
      merchantOptions: [],
      merchantTabOptions: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      merchantNickName: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status:null,
        taskId: null,
        taskName:"",
        type:2,
        isInvoicing: null,
        organizationType:4,
        invoiceCatagory: null,
        receiverCompanyName: null
      },
      queryCooperateTsl: {
        type: 2,
        pageNum: 1,
        maxPageNum: 0,
        pageSize: 100,
        initiateCompanyName: null,
        tslId: null,
        isAsc: 'desc'
      },
      invoiceTaskQuery:{
        pageNum: 1,
        pageSize: 10,
        invoiceId:null,
      },
      form: {
        tslId: null,
        taskAmount: 0,
        invoiceFile: '',
        merchantId: null,
        merchantNickName: null,
        invoiceCatagory: ''
      },
      payslipId: null,
      payslipList: [],
      invoiceTaskTotal:0,
      invoiceTaskList:[],
      organizationType: store.getters.organizationType,
    }
  },
  created() {

  },
  mounted() {
    this.loading = true
    this.getList()

    // listCooperativeTax(this.queryCooperateTsl).then(response => {
    //   this.merchantOptions = response.rows
    //   this.queryCooperateTsl.maxPageNum = Math.ceil(response.total / 100)
    //   if (this.merchantOptions.length > 0) {
    //     // this.queryParams.receiverUserId = this.merchantOptions[0].userId
    //
    //   }
    // }).catch(() => {
    //   this.loading = false
    // })

  },
  methods: {

    getList() {
      this.loading = true
      listInvoice(this.queryParams).then(response => {
        this.payslipList = response.rows
        this.total = response.total
        this.setSelected()
        this.loading = false
      }).catch(() => {
        this.loading = true
      })
    },

    setSelected() {
      this.payslipList.forEach(item => {
        const isSelected = this.selectedRowKeys.find(row => item.id === row.id)
        item._selected = isSelected
        if (isSelected) {
          this.$nextTick(() => {
            this.$refs.table.toggleRowSelection(item, isSelected)
          })
        }
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    handleTaskRemote(query) {
      if (query !== '') {
        this.taskLoading = true
        listTask({ taskName: query }).then(response => {
          this.taskOptions = response.rows
          this.taskLoading = false
        }).catch(() => {
          this.taskLoading = false
        })
      }
    },
    handleSelectionChange(selection, row) {
      const isAdd = selection.some((selectRow) => selectRow.id === row.id)
      if (isAdd) {
        if (this.selectedRowKeys.length >= 1000) {
          this.$message.warning('最多选择1000条')
        }
      }
      this.handleRowChangeAll(row, isAdd)
    },
    handleSelectionAllChange(selection) {
      let isAdd = true
      let changeSelect = selection.slice()

      if (!changeSelect.length) {
        isAdd = false
        changeSelect = this.payslipList.slice()
      }
      if (isAdd) {
        if (this.selectedRowKeys.length >= 1000) {
          this.$message.warning('最多选择1000条')
        }
      }

      for (let i = 0; i < changeSelect.length; i++) {
        const row = changeSelect[i]
        // 检查是否应该终止循环
        this.handleRowChangeAll(row, isAdd)
      }
    },
    handleRowChangeAll(row, isAdd) {
      const index = this.selectedRowKeys.findIndex(
        item => item.id === row.id
      )
      let taskAmount = row.successAmount + row.successMerchantAmount
      if (!taskAmount) {
        taskAmount = 0
      }
      const precision = 100 // 用于处理两位小数
      if (index === -1) {
        if (isAdd) {
          // 预检查添加后的数量
          if (this.selectedRowKeys.length >= 1000) {
            this.$refs.table.toggleRowSelection(row, false)
          } else {
            if (this.form.invoiceCatagory == null || this.form.invoiceCatagory === '') {
              this.form.invoiceCatagory = row.invoiceCatagory
            } else {
              this.form.invoiceCatagory = this.form.invoiceCatagory + ' | ' + row.invoiceCatagory
            }
            this.selectedRowKeys.push({ id: row.id })
            this.form.taskIds.push(row.taskId)
            this.form.payslipIds.push(row.id)
            const result = (this.form.taskAmount * precision + taskAmount * precision) / precision
            this.form.taskAmount = result.toFixed(2)
          }
        }
      } else {
        if (!isAdd) {
          let invoiceCatagory = this.form.invoiceCatagory.split('|')
          invoiceCatagory.splice(index, 1)
          this.form.taskIds.splice(index, 1)
          this.form.payslipIds.splice(index, 1)
          this.form.invoiceCatagory = invoiceCatagory
          this.selectedRowKeys.splice(index, 1)
          const result = (this.form.taskAmount * precision - taskAmount * precision) / precision
          this.form.taskAmount = result.toFixed(2)
        }
      }
      return false
    },

    handleInvoice(row) {
      this.form = row
      this.invoiceOpen = true
    },


    handleDetail(row){
      this.detailOpen = true
      this.form = row
      if (row.id){
        this.invoiceTaskQuery.invoiceId = row.id
      }
      listInvoiceTask(this.invoiceTaskQuery).then(res=>{
        this.invoiceTaskList = res.rows
        this.invoiceTaskTotal = res.total
      })
    },

    subInvoice() {
      if (!this.form.invoiceFile){
        this.$message.warning("请上传发票");
        return
      }
      this.$modal.confirm('确定要提交这些任务吗？').then(() => {
        this.invoiceLoading = true
        submitPayslipInvoice(this.form).then(res => {
          this.invoiceLoading = false
          this.invoiceOpen = false
          this.getList()
        }).catch(() => {
          this.invoiceLoading = false
        })
      })

    },

    handleMerchantRemote() {
      // 检查是否还有更多数据
      if (this.queryCooperateTsl.maxPageNum <= this.queryCooperateTsl.pageNum) {
        return
      }
      this.queryCooperateTsl.pageNum++
      listCooperativeTax(this.queryCooperateTsl).then(response => {
        // 更新总页数
        this.queryCooperateTsl.maxPageNum = Math.ceil(response.total / 100)
        // 合并数据
        this.merchantOptions = [...this.merchantOptions, ...response.rows]
      }).catch(() => {
      })
    },
    handleNodeClick(row) {
      this.$refs.tree.setCheckedKeys([])
      this.$refs.tree.setCheckedKeys([row.initiateOrganizationId])
      this.queryParams.initiateOrganizationId = row.initiateOrganizationId
      this.merchantNickName = row.merchantNickName
      this.form.initiateOrganizationId = row.initiateOrganizationId
      this.getList()
    },

    totalAmount(amount) {
      const tax = this.safeAdd(0, amount * 0.06) // 确保 tax 至少为 0

      return this.formattedTotal(this.safeAdd(amount, tax))
    },
    safeAdd(a, b) {
      return (Math.round(a * 100) + Math.round(b * 100)) / 100
    },

    formattedTotal(amount) {
      const formatter = new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })

      return formatter.format(amount)
    },
    /** 导出按钮操作 */
    handleExport() {

      this.download('invoice/invoice/export', {
        ...this.queryParams
      }, `待开票_${new Date().getTime()}.xlsx`)
    }
  },
  watch: {
    'queryCooperateTsl.initiateCompanyName': {
      handler(val) {
        this.queryCooperateTsl.maxPageNum = 1
        this.queryCooperateTsl.pageNum = 0
        this.merchantOptions = []
        this.handleMerchantRemote(val)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.infinite-list-wrapper {
  max-height: calc(100vh - 180px);
}
</style>
